"""
@date: 2023/7/11
@author: gaohui
@desc: test

"""
'''
- 通过ip请求淘宝的一个接口获取到省份和运营商
- 接口：https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=要查询的ip地址
- 每一行变成这种形式保存到文件
- 格式：ip,中国,湖南,电信

总之：
定义一个函数 去接收一个ip 地址，然后得到ip的基本信息，取ip，取国家 身份 运营商 取到之后用 ，隔开保存到文件中
'''
import requests

def get_message(address: str) -> str:
    url = f"https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip={address}"
    try:
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()["data"]
        country = data["country"]
        region = data["region"]
        isp = data["isp"]
        return f"{address},{country},{region},{isp}"
    except requests.exceptions.HTTPError as e:
        print(f"请求失败：{e}")
        return ""
    except Exception as e:
        print(f"发生错误：{e}")
        return ""

result = get_message(input("请输入您要查询的ip地址:"))

if result:
    with open("ip.txt", "a", encoding="utf-8") as fp:
        fp.write(result + "\n")
else:
    print("无法获取IP信息！")

print("成功获取IP信息！")

